package com.xhs.service;

import com.xhs.dto.request.ContentRequest;
import com.xhs.entity.Content;
import com.xhs.entity.User;
import com.xhs.entity.ViewHistory;
import com.xhs.repository.ContentRepository;
import com.xhs.repository.ViewHistoryRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
import java.util.UUID;

/**
 * 内容服务
 */
@Service
@Transactional
public class ContentService {
    
    @Autowired
    private ContentRepository contentRepository;
    
    @Autowired
    private ViewHistoryRepository viewHistoryRepository;
    
    @Value("${app.upload.path}")
    private String uploadPath;
    
    /**
     * 创建内容
     */
    public Content createContent(ContentRequest request, MultipartFile file, User author) throws IOException {
        // 保存文件
        String fileName = saveFile(file);
        String fileUrl = "/uploads/" + fileName;
        
        Content content = new Content();
        content.setTitle(request.getTitle());
        content.setDescription(request.getDescription());
        content.setType(request.getType());
        content.setFileUrl(fileUrl);
        content.setFileSize(file.getSize());
        content.setMimeType(file.getContentType());
        content.setTags(request.getTags());
        content.setPublished(request.getPublished());
        content.setDuration(request.getDuration());
        content.setAuthor(author);
        
        return contentRepository.save(content);
    }
    
    /**
     * 更新内容
     */
    public Content updateContent(Long id, ContentRequest request, User user) {
        Content content = contentRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("内容不存在"));
        
        // 检查权限
        if (!content.getAuthor().getId().equals(user.getId()) && !user.getRole().equals(User.Role.ADMIN)) {
            throw new RuntimeException("无权限修改此内容");
        }
        
        // 只允许修改特定字段
        content.setTitle(request.getTitle());
        content.setDescription(request.getDescription());
        content.setTags(request.getTags());
        content.setPublished(request.getPublished());
        
        return contentRepository.save(content);
    }
    
    /**
     * 删除内容
     */
    public void deleteContent(Long id, User user) {
        Content content = contentRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("内容不存在"));
        
        // 检查权限
        if (!content.getAuthor().getId().equals(user.getId()) && !user.getRole().equals(User.Role.ADMIN)) {
            throw new RuntimeException("无权限删除此内容");
        }
        
        contentRepository.delete(content);
    }
    
    /**
     * 获取内容详情
     */
    public Optional<Content> getContentById(Long id) {
        return contentRepository.findById(id);
    }
    
    /**
     * 记录内容访问
     */
    public void recordView(Long contentId, User user) {
        Content content = contentRepository.findById(contentId)
                .orElseThrow(() -> new RuntimeException("内容不存在"));
        
        // 增加访问次数
        content.incrementViewCount();
        contentRepository.save(content);
        
        if (user != null) {
            // 记录用户访问历史
            Optional<ViewHistory> existingView = viewHistoryRepository.findByUserAndContent(user, content);
            if (existingView.isPresent()) {
                ViewHistory viewHistory = existingView.get();
                viewHistory.setLastViewedAt(LocalDateTime.now());
                viewHistoryRepository.save(viewHistory);
            } else {
                ViewHistory viewHistory = new ViewHistory();
                viewHistory.setUser(user);
                viewHistory.setContent(content);
                viewHistory.setLastViewedAt(LocalDateTime.now());
                viewHistoryRepository.save(viewHistory);
            }
        }
    }
    
    /**
     * 获取推荐内容
     */
    public Page<Content> getRecommendedContents(User user, int page, int size) {
        Pageable pageable = PageRequest.of(page, size);
        
        // 暂时简化推荐逻辑，直接返回按点赞数排序的内容
        return contentRepository.findRecommendedContents(pageable);
    }
    
    /**
     * 搜索内容
     */
    public Page<Content> searchContents(String keyword, int page, int size) {
        Pageable pageable = PageRequest.of(page, size);
        return contentRepository.findByTitleContainingAndPublishedTrue(keyword, pageable);
    }
    
    /**
     * 获取用户的内容
     */
    public Page<Content> getUserContents(User user, int page, int size) {
        Pageable pageable = PageRequest.of(page, size);
        return contentRepository.findByAuthorOrderByCreatedAtDesc(user, pageable);
    }
    
    /**
     * 获取已发布的内容
     */
    public Page<Content> getPublishedContents(int page, int size) {
        Pageable pageable = PageRequest.of(page, size);
        return contentRepository.findByPublishedTrueOrderByCreatedAtDesc(pageable);
    }
    
    /**
     * 获取下一个内容
     */
    public Optional<Content> getNextContent(Long currentId) {
        List<Content> contents = contentRepository.findNextContent(currentId, PageRequest.of(0, 1));
        return contents.isEmpty() ? Optional.empty() : Optional.of(contents.get(0));
    }
    
    /**
     * 获取上一个内容
     */
    public Optional<Content> getPreviousContent(Long currentId) {
        List<Content> contents = contentRepository.findPreviousContent(currentId, PageRequest.of(0, 1));
        return contents.isEmpty() ? Optional.empty() : Optional.of(contents.get(0));
    }
    
    /**
     * 保存上传的文件
     */
    private String saveFile(MultipartFile file) throws IOException {
        // 创建上传目录
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
        }
        
        // 生成唯一文件名
        String originalFilename = file.getOriginalFilename();
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName = UUID.randomUUID().toString() + extension;
        
        // 保存文件
        Path filePath = Paths.get(uploadPath, fileName);
        Files.copy(file.getInputStream(), filePath);
        
        return fileName;
    }
} 